package com.bracelet.controller;

import com.bracelet.beans.Msg;
import com.bracelet.beans.Token;
import com.bracelet.beans.User;
import com.bracelet.service.LoginService;
import com.bracelet.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {
    @Autowired
    LoginService loginService;

    @ResponseBody
    @RequestMapping(value = "/login")
    public Msg Login(HttpServletRequest request, HttpServletResponse response){
       // System.out.println(request.getHeader("token"));
        String username = (String) request.getAttribute("username");
        String password = (String) request.getAttribute("password");
        User user = new User();
        // Msg msg = new Msg();
        user.setUsername(username);
        user.setPassword(password);
        User user1 = loginService.Login(user);
        if(user1 != null){
            Token token  = new Token();
            token.setId(user1.getUserid());
            token.getExtend().put("username",user1.getUsername());
            String  token1 = JWTUtils.sign(token,10*60*1000);
            response.setHeader("token",token1);
            return Msg.success();
        }else{
            return Msg.fail();
        }
    }
}